<?php

namespace app\api\controller\web;

use app\admin\model\Project;
use app\admin\model\project\Progress;
use app\admin\model\Subject;
use app\admin\model\Type;
use app\admin\model\User;
use app\common\common\Common;
use app\common\common\PerServer;
use app\common\controller\Api;
use app\common\handler\TimeHandler;
use app\common\helpers\ImageUtil;
use fast\Tree;
use think\Db;
use think\Log;
use think\Model;
use think\Validate;


class Index extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $model ='';
    public function _initialize()
    {
        parent::_initialize();
    }


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取用户列表
     */
    public function getUserList(){
       $search = $this->request->param('search');
       $model = (new User())->alias('u')
           ->field('u.id,realname,job_name')
           ->join('project_job j','job_id = j.id','left')
           ->where('realname','not in',['',null])
           ->where('status','normal');
       if($search){
           $model->where('realname','like','%'.$search.'%');
       }
      $list =  $model->select();
      $this->success("获取成功",$list);
    }

    /**
     * 搜索条件
     */
    public function searchList(){

        $user = $this->auth->getUserinfo();
        $model = (new Type());
        if($user['user_permissions'] != '5'){ //不是储备项目池管理 就不返回对应的类型
            $model->where('id','<>','6');
        }
        $type = $model->select();
        $Subject = Subject::all();
        $this->success("获取成功" ,[
            'type_list'=>array_column($type,'type_name','id'),
            'subject_list'=>array_column($Subject,'subject_name','id'),
            'is_lx' => Common::$is_lx_list
        ]);
    }

    /**
     * 项目列表
     */
    public function projectList()
    {
        $user = $this->auth->getUserinfo();
        $page = $this->request->param('page',1);//页码
        $pageSize = $this->request->param('pageSize',10);//每页展示数量
        $area_id = $this->request->param('area_id');//区域
        $subject_id = $this->request->param('subject_id');//主体
        $type_id = $this->request->param('type_id');//类型
        $is_lx = $this->request->param('is_lx');//是否提现
        $search = $this->request->param('search');//
        if($type_id){
            if($type_id == '6'){ //查看是储备项目池管理 就需要权限或是否指派
                if($user['user_permissions'] != '5'){ //如果没有权限只能看给自己指派的项目
                    $where['head_user_id'] = $user['user_id'];
                }
            }else{
                if(!PerServer::getInstance()->isAuth(3)){ //看权限返回数据
                    $where['user_id'] = $user['user_id'];
                }
            }
            $where['type_id'] = $type_id;
        }else{
            $this->error("请选择查看的类型");
        }
        $where['is_del']=0;
        if($is_lx != ''){
            $where['is_lx'] = $is_lx;
        }
        if($subject_id){
            $where['subject_id'] = $subject_id;
        }
        if($area_id){
            $where['area_id'] = $area_id;
        }
        if($search){
            $where['project_name'] = ['like','%'.$search.'%'];
        }
        $model = (new Project())->field('id,project_logo,status,project_name,project_no,upload_time')
                ->where($where)
                ->order('upload_time desc')
                ->paginate($pageSize, '', ['page' => $page, 'list_rows' => $pageSize]);

        $total= $model->total();
        $list =  $model->items();
        if($list){
            foreach ($list as $v){
                $v['project_logo'] = ImageUtil::handle($v['project_logo']);
            }
        }
        $result = array("total" =>$total , "list" => $list);
        $this->success("获取成功",$result);;
    }

    /**
     * 创建项目
     */
    public function projectCreate(){
        $user = $this->auth->getUserinfo();
        if(!PerServer::getInstance()->isAuth(1)){ //看是否有权限新增
            $this->error("权限不足");
        }
        $validate = new \think\Validate([
            ['project_name', 'require', '项目名称不能为空'],
//            ['project_logo', 'require', '项目logo不能为空'],
            ['subject_id', 'require', '主体不能为空'],
            ['type_id', 'require', '类型不能为空'],
            // ['project_no', 'require', '项目编号不能为空'],
            ['project_leader', 'require', '项目负责人不能为空'],
            ['pocket_unit', 'require', '兜底单位不能为空'],
            ['is_lx', 'require', '立项不能为空'],
            ['status', 'require', '项目状态不能为空'],
//            ['project_priority', 'require', '项目优先级不能为空'],

            ['pay_status', 'require', '付款状态不能为空'],
            ['filings_status', 'require', '备案状态不能为空'],
            ['approval_status', 'require', '批复状态不能为空'],
            ['area_id', 'require', '区域不能为空'],

        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }

        $pay_status = $this->request->param('pay_status');
        $pay_money = $this->request->param('pay_money');
        $zj_num = $this->request->param('zj_num');
        $zj_num_mwh = $this->request->param('zj_num_mwh');
        $filings_status = $this->request->param('filings_status');
        $approval_status = $this->request->param('approval_status');
        $area_id = $this->request->param('area_id');

//        $project_priority = $this->request->param('project_priority');
        $project_logo = $this->request->param('project_logo','');
        $project_name = $this->request->param('project_name');
        $subject_id = $this->request->param('subject_id');
        $type_id = $this->request->param('type_id');
        // $project_no = $this->request->param('project_no');
        $project_leader = $this->request->param('project_leader');
        $pocket_unit = $this->request->param('pocket_unit');
        $is_lx = $this->request->param('is_lx');
        $status= $this->request->param('status','1');
        $project_content = $this->request->param('project_content');
        $project_pics = $this->request->param('project_pics');
        $imgArr = explode(',',$project_pics);
        if(count($imgArr)>6){
            $this->error("图片最多上传6张");
        }

        $ProjectInfo = Project::get(['project_name'=>$project_name]);
        if($ProjectInfo){
            $this->error("该项目名称已存在");
        }
        $Subject =Subject::get(['id'=>$subject_id]);
        if(!$Subject){
            $this->error("主体不存在");
        }
        $Type = Type::get(['id'=>$type_id]);
         if(!$Type){
            $this->error("类型不存在");
        }
        $data=[
            'user_id'=>$user['user_id'],
            'project_logo'=>$project_logo, //项目logo
            'project_name'=>$project_name, //项目名称
            'subject_id'=>$subject_id, //主体id
            'type_id'=>$type_id, //类型id
            'project_leader'=>$project_leader, //项目负责人
//             'project_no'=>$project_no, //项目编号
            'pocket_unit'=>$pocket_unit, //兜底单位
            'is_lx'=>$is_lx, //是否立项
//            'project_priority'=>$project_priority,
            'status'=>$status,  //完成状态
            'project_content'=>$project_content, //项目内容
            'project_pics'=>$project_pics,
            'upload_time'=>date('Y-m-d H:i:s'), //上传时间
            'pay_status'=>$pay_status, //付款状态
            'pay_money'=>$pay_money,  //付款金额
            'zj_num'=>$zj_num,  //装机量
            'zj_num_mwh'=>$zj_num_mwh,  //装机量
            'filings_status'=>$filings_status,  //备案状态
            'approval_status'=>$approval_status,  //批复状态
            'area_id'=>$area_id,   //区域
        ];

        Db::startTrans();
        try {
            $info = Project::create($data);
            $project_no = $Subject['code'].$Type['code'].Common::$is_lx_code[$is_lx].str_pad($info['id'],6,'0',STR_PAD_LEFT);
            Project::update(['project_no'=>$project_no],['id'=>$info['id']]);
            \app\api\controller\Common::userOperatelog($info['id'],'新增',1);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            \app\api\controller\Common::userOperatelog($info['id'],'新增',2);
            $this->error($e->getMessage());
        }
        $this->success("提交成功");
    }

    /**
     * 删除项目
     */
    public function projectdel(){

        $user = $this->auth->getUserinfo();
        $project_id = $this->request->param('project_id');
        if(!PerServer::getInstance()->isAuth(2)){ //看是否有权限删除
           $data =  Project::get(['id'=>$project_id]);
           if($data['user_id'] != $user['id']){
               $this->error("权限不足");
           }
        }
        $info = Project::update(['is_del'=>1],['id'=>$project_id]);
        if($info){
            \app\api\controller\Common::userOperatelog($project_id,'删除',1);
            $this->success("删除成功");
        }
        \app\api\controller\Common::userOperatelog($project_id,'删除',2);
        $this->error("删除失败");
    }


    /**
     * 项目详情
     */
    public function projectInfo(){
        $user = $this->auth->getUserinfo();
        $project_id = $this->request->param('project_id');
        $type= $this->request->param('type',1);
        $info = Project::get(['id'=>$project_id]);

        if($info) {
            if ($type == 1) {
                if (!PerServer::getInstance()->isAuth(3)) { //看是否有权限查看
                    if ($info['type_id'] == '6') {
                        if ($info['head_user_id'] != $user['id']) {
                            $this->error("权限不足");
                        }
                    } else {
                        if($info['user_id'] != $user['id']){
                            $this->error("权限不足");
                       }

                    }
                }
            }elseif ($type == 2){
                $info2 = Db::name('user_msg')->where(['project_id'=>$project_id,'push_user_id'=>$user['id']])->find();
                if(!$info2){
                    $this->error("权限不足");
                }
                $this->success("获取成功", $info);
            } else{
                $info3 = Db::name('user_msg_log')->where(['project_id'=>$project_id,'accept_user_id'=>$user['id']])->find();
                if(!$info3){
                    $this->error("权限不足");
                }
            }
            \app\api\controller\Common::userOperatelog($project_id, '查看', 1);
            $info['user_name'] = $user['nickname'];
            $typeList = array_column(Type::all(),'type_name','id');
            $info['type_name'] = isset($typeList[$info['type_id']]) ? $typeList[$info['type_id']] : '';
            $this->success("获取成功", $info);
        }


        \app\api\controller\Common::userOperatelog($project_id,'查看',2);
        $this->error("获取失败");
    }

    /**
     * 修改项目
     */
    public function projectUpd(){
        $validate = new \think\Validate([
            ['project_id', 'require', '项目id不能为空'],
            ['project_name', 'require', '项目名称不能为空'],
//             ['project_logo', 'require', '项目logo不能为空'],
            ['subject_id', 'require', '主体不能为空'],
            ['type_id', 'require', '类型不能为空'],
            ['project_no', 'require', '项目编号不能为空'],
            ['project_leader', 'require', '项目负责人不能为空'],
            ['pocket_unit', 'require', '兜底单位不能为空'],
            ['is_lx', 'require', '立项不能为空'],
            ['status', 'require', '项目状态不能为空'],
//            ['project_priority', 'require', '项目优先级不能为空'],

            ['pay_status', 'require', '付款状态不能为空'],
            ['filings_status', 'require', '备案状态不能为空'],
            ['approval_status', 'require', '批复状态不能为空'],
            ['area_id', 'require', '区域不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $pay_status = $this->request->param('pay_status');
        $pay_money = $this->request->param('pay_money');
        $zj_num = $this->request->param('zj_num');
        $zj_num_mwh = $this->request->param('zj_num_mwh','');
        $filings_status = $this->request->param('filings_status');
        $approval_status = $this->request->param('approval_status');
        $area_id = $this->request->param('area_id');

        $project_id = $this->request->param('project_id');
         $project_logo = $this->request->param('project_logo','');
//        $project_priority = $this->request->param('project_priority');
        $project_name = $this->request->param('project_name');
        $subject_id = $this->request->param('subject_id');
        $type_id = $this->request->param('type_id');
//        $project_no = $this->request->param('project_no');
        $project_leader = $this->request->param('project_leader');
        $pocket_unit = $this->request->param('pocket_unit');
        $is_lx = $this->request->param('is_lx');
        $status= $this->request->param('status');
        $project_content = $this->request->param('project_content');
        $project_pics = $this->request->param('project_pics');
        $imgArr = explode(',',$project_pics);
        if(count($imgArr)>6){
            $this->error("图片最多上传6张");
        }
        $user = $this->auth->getUserinfo();
        if(!PerServer::getInstance()->isAuth(1)){ //看是否有权限修改
            $data2 =  Project::get(['id'=>$project_id]);
            if($data2['user_id'] != $user['id']){
                $this->error("权限不足");
            }
        }
        $ProjectInfo = Project::get(['project_name'=>$project_name]);
        if($ProjectInfo && $ProjectInfo['id'] != $project_id){
            $this->error("该项目名称已存在");
        }
         $Subject =Subject::get(['id'=>$subject_id]);
        if(!$Subject){
            $this->error("主体不存在");
        }
        $Type = Type::get(['id'=>$type_id]);
         if(!$Type){
            $this->error("类型不存在");
        }
        $project_no = $Subject['code'].$Type['code'].Common::$is_lx_code[$is_lx].str_pad($project_id,6,'0',STR_PAD_LEFT);
         $data=[
             'project_logo'=>$project_logo, //项目logo
            'project_name'=>$project_name, //项目名称
            'subject_id'=>$subject_id, //主体id
            'type_id'=>$type_id, //类型id
            'project_leader'=>$project_leader, //项目负责人
            'project_no'=>$project_no, //项目编号
            'pocket_unit'=>$pocket_unit, //兜底单位
            'is_lx'=>$is_lx, //是否立项
//            'project_priority'=>$project_priority,
            'status'=> $status,  //完成状态
            'project_content'=>$project_content, //项目内容
            'project_pics'=>$project_pics,
            'update_time'=>date('Y-m-d H:i:s'), //更新时间

             'pay_status'=>$pay_status, //付款状态
             'pay_money'=>$pay_money,  //付款金额
             'zj_num'=>$zj_num,  //装机量
             'zj_num_mwh'=>$zj_num_mwh,  //装机量
             'filings_status'=>$filings_status,  //备案状态
             'approval_status'=>$approval_status,  //批复状态
             'area_id'=>$area_id,   //区域
        ];
        $info = Project::update($data,['id'=>$project_id]);
        if($info){
            \app\api\controller\Common::userOperatelog($project_id,'修改',1);
            $this->success("提交成功");
        }
        \app\api\controller\Common::userOperatelog($project_id,'修改',2);
        $this->error("提交失败");
    }

    /**
     * 项目进程
     */
    public function projectProcess(){
        $user = $this->auth->getUserinfo();
        $validate = new \think\Validate([
            ['project_id', 'require', '项目id不能为空'],
            ['start_time', 'require', '开始时间不能为空'],
            ['end_time', 'require', '结束时间不能为空'],
            ['content', 'require', '内容不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $project_id= $this->request->param('project_id');
        $info = Project::get(['id'=>$project_id]);
        if(!$info){
            $this->error('不存在该项目');
        }
        if($info && $info['status'] == '3'){
            $this->error('该项目已完成不能进行添加进程');
        }
        $start_time = $this->request->param('start_time');
        $end_time = $this->request->param('end_time');
        $content = $this->request->param('content');
        $data=[
            'user_id'=>$user['user_id'], //用户id
            'project_id'=>$project_id, //项目id
            'start_time'=>$start_time, //阶段开始时间
            'end_time'=>$end_time, //阶段结束时间
            'content'=>$content, //内容
            'createtime'=>date('Y-m-d H:i:s'), //创建时间
        ];
        $result = Db::name('project_progress')->insert($data);
        if(!$result) {
            \app\api\controller\Common::userOperatelog($project_id,'新增项目进程',2,-1);
            Project::update(['phase_update_time'=>date('Y-m-d H:i:s')],['id'=>$project_id]);
            $this->error("新增失败");
        }
        $progressId = Db::name('project_progress')->getLastInsID();
        \app\api\controller\Common::userOperatelog($project_id,'新增项目进程',1,$progressId);
        $this->success("新增成功");
    }

    /**
     * 项目进程列表
     */
    public function projectProcessList(){
        $project_id = $this->request->param('project_id');
        $list = (new Progress())->field('start_time,end_time,content')->where(['project_id'=>$project_id])->select();
        $this->success("获取成功",$list);
    }

    /**
     * 评论项目
     */
    public function comment(){
        $user = $this->auth->getUserinfo();
        $validate = new \think\Validate([
            ['project_id', 'require', '项目id不能为空'],
            ['content', 'require', '内容'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $project_id= $this->request->param('project_id');
        $info = Project::get(['id'=>$project_id]);
        if(!$info){
            $this->error('不存在该项目');
        }
        $content = $this->request->param('content');
        $data=[
            'user_id'=>$user['user_id'], //用户id
            'project_id'=>$project_id, //项目id
            'content'=>$content, //内容
            'createtime'=>date('Y-m-d H:i:s'), //创建时间
        ];
        $result = Db::name('project_comment')->insert($data);
        if(!$result) $this->error("评论失败");
        $this->success("评论成功");
    }

    /**
     * 获取项目评论
     */
    public function projectComment(){
        $validate = new \think\Validate([
            ['project_id', 'require', '项目id不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $project_id= $this->request->param('project_id');

        $result = Db::name('project_comment')->alias('pc')
            ->field('nickname,avatar,content')
            ->join('user u','pc.user_id = u.id','left')
            ->where(['project_id'=>$project_id])
            ->order('pc.createtime desc')
            ->select();
        $this->success("获取成功",$result);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 项目进程没更新就提醒
     */
    public function projectPemind(){
        $user = $this->auth->getUserinfo();

        $time = date('Y-m-d H:i:s');

        $list = (new Project)
                ->field('id,upload_time,phase_update_time')
                ->where(['is_del'=>'0'])
                ->where(['user_id'=>$user['id']])
                ->where('status',"<>",'3')
                ->select();
        $result = false;
        $num = 0 ;
        if($list){
            foreach ($list as $v){
                if($v['phase_update_time']){
                    $phase_update_time = date('Y-m-d H:i:s',strtotime("+ 7 day", strtotime($v['phase_update_time'])));
                    if($phase_update_time < $time) {
                        $result = true;
                        $num ++;
                        Project::update(['phase_update_time'=>date('Y-m-d H:i:s')],['id'=>$v['id']]);
                    }
                }else{
                    $update_time = date('Y-m-d H:i:s',strtotime("7 day", strtotime($v['upload_time'])));
                    if($update_time < $time) {
                        $result = true;
                        $num ++;
                        Project::update(['phase_update_time'=>date('Y-m-d H:i:s')],['id'=>$v['id']]);
                    }
                }
            }
        }

        $this->success("你有".$num."个未完成项目已超过七天未更新进程",$result);
    }

}
